package group2.controller;

import group2.model.ReceiveAddress;
import group2.model.UserInfo;
import group2.service.IReceiveAddressService;
import group2.service.UserService;
import group2.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 周祖航
 * @date 2020/8/24 002416:38
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    IReceiveAddressService receiveAddressService;


    //用户登陆
    @RequestMapping("/userlogin")
    @ResponseBody
    public Map<String,Object> login(UserInfo user, HttpSession session){
        Map<String,Object> map=new HashMap<>();
        try {
            UserInfo loguser = userService.login(user);

            if(loguser!=null) {
                Map<String,String> payload = new HashMap<>();
                payload.put("userId", loguser.getUserId());
                payload.put("userName", loguser.getUserName());
                payload.put("address", loguser.getAddress());
                payload.put("phone", loguser.getPhone());
                //生成token
                String token = JWTUtil.getToken(payload);

                map.put("userName", loguser.getUserName());
                map.put("state", true);
                map.put("msg", "登录成功");
                map.put("token",token);
            }
            else {
                map.put("state", false);
                map.put("msg", "登录失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "登录失败");
        }
        return map;
    }
    /*
     * 注册用户
     *
     * */
    @RequestMapping("/register")
    @ResponseBody
    public Map<String,Object> register(UserInfo user){
        Map<String,Object> map=new HashMap<>();
            boolean reguser=userService.selectByname(user);
            //true为存在该用户
          try {
              if (!reguser) {
                  userService.register(user);
                  map.put("regState", true);
                  map.put("msg", "注册成功");
                  //添加默认地址
                  ReceiveAddress receiveAddress = new ReceiveAddress(user.getAddress(),user.getPhone(),user.getUserName());
                  this.receiveAddressService.addAddressYes(receiveAddress,user.getUserId());
              } else {
                  map.put("regState", false);
                  map.put("msg", "注册失败，已存在该用户");
              }
          }catch (Exception e){
              e.printStackTrace();
          }
        return map;
    }
}
